package com.ptszyxx.popose.module.main.expression;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.databinding.FragmentExpressionBinding;
import com.ptszyxx.popose.module.main.expression.adapter.ExpressionAdapter;
import com.ptszyxx.popose.module.main.expression.vm.ExpressionVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.expression.ExpressionEntity;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;

import java.util.List;

/**
 * 自定义常用语
 */
public class ExpressionFragment extends BaseFragment<FragmentExpressionBinding, ExpressionVM> {
    private ExpressionAdapter adapter;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_expression;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ExpressionVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(ExpressionVM.class);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestExpression();
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new ExpressionAdapter();
        binding.refreshView.initAdapter(adapter);

        adapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ExpressionEntity entity = (ExpressionEntity)adapter.getData().get(position);
                showDialogDel(entity);
                return true;
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, o -> setAdapter((List<ExpressionEntity>)o));
    }

    private void setAdapter(List<ExpressionEntity> list) {
        binding.refreshView.setAdapterUI(adapter, list, true);
    }

    private void showDialogDel(ExpressionEntity entity){
        YDialogUtil.getInstance().showConfirm(getContext(), "确定要删除吗？")
                .setOnConfirmListener(()-> viewModel.requestExpressionDel(entity));
    }
}
